import mongoose from '../config/DBHelper'
import moment from 'moment'
const Schema = mongoose.Schema
const CommentSchema = new Schema({
  tid: { type: String, ref: 'post' },
  tuid: { type: String, ref: 'user' },
  cuid: { type: String, ref: 'user' },
  content: { type: String },
  created: { type: Date },
  hands: { type: Number, default: 0 },
  status: { type: Number, default: 1 },
  isRead: { type: Number, default: 0 },
  isBest: { type: Number, default: 0 }
})

CommentSchema.pre('save', function (next) {
  this.created = moment().format('YYYY-MM-DD HH:mm:ss')
  next()
})

CommentSchema.statics = {
  getCommentList (tid, page, limit) {
    return this.find({
      tid
    }).populate({
      path: 'cuid',
      select: 'name isVip status pic _id'
      // match: { status: { $eq: 0 } } // 是否被禁用
    }).populate({
      path: 'tid',
      select: '_id title status'
    }).skip(page * limit).limit(limit)
  },
  queryCount (tid) {
    return this.find({ tid }).countDocuments()
  },
  getUserCommentList (uid, page, limit) {
    return this.find({
      cuid: uid
    }).skip(page * limit).populate({
      path: 'tid',
      select: '_id title'
    }).limit(limit).sort({ created: -1 })
  },
  getUserMsgList (uid, page, limit) {
    return this.find({
      tuid: uid,
      cuid: {
        $ne: uid
      },
      status: 1,
      isRead: 0
    })
      .populate({
        path: 'cuid',
        select: 'name isVip status pic _id'
      }).populate({
        path: 'tid',
        select: '_id title status'
      })
      .skip(page * limit).limit(limit)
  },
  getUserMsgCount (uid) {
    return this.find({
      tuid: uid,
      cuid: {
        $ne: uid
      },
      status: 1,
      isRead: 0
    }).countDocuments()
  }
}
const Comment = mongoose.model('comment', CommentSchema)

export default Comment
